<template>
  <div class="pane-account">
    <el-form
      ref="formRef"
      :model="account"
      :rules="accountRules"
      label-width="60px"
      size="large"
      status-icon
    >
      <el-form-item label="帐号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import useLoginStore from '@/store/login/login'
import type { FormRules, ElForm } from 'element-plus'
import { reactive, ref } from 'vue'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'

const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'

const account = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})

const accountRules: FormRules = {
  name: [
    { required: true, message: '帐号不能为空', trigger: 'blur' },
    { pattern: /^[a-z0-9]{6,10}$/, message: '长度必须在6到10位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度必须在6到10位之间', trigger: 'blur' }
  ]
}

// 登录
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()

function loginAction(isRemPwd: boolean) {
  formRef.value?.validate((valid) => {
    if (valid) {
      const name = account.name
      const password = account.password
      loginStore.loginAccountAction({ name, password }).then((res) => {
        // 记住密码
        if (isRemPwd) {
          localCache.setCache(CACHE_NAME, account.name)
          localCache.setCache(CACHE_PASSWORD, account.password)
        } else {
          localCache.removeCache(CACHE_NAME)
          localCache.removeCache(CACHE_PASSWORD)
        }
      })
    } else {
      ElMessage.error('请输入帐号和密码')
    }
  })
}

defineExpose({
  loginAction
})
</script>

<style lang="less" scoped></style>
